<template>
  <div class="liveEditOrAdd" style="height： 100vh;">
    <div class="crumbs-box">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/activity/list?tabsName=Live' }">活动管理</el-breadcrumb-item>
        <el-breadcrumb-item v-if="$route.query && $route.query.param">编辑在线课程</el-breadcrumb-item>
        <el-breadcrumb-item v-else>添加在线课程</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="content-box">
      <div class="live-title">发布在线课程</div>

      <div class="teaching-box">
        <div class="title">在线课程信息</div>

        <el-form
          v-if="ruleForm"
          ref="ruleForm"
          :rules="rules"
          class="teaching-form"
          label-width="100px"
          :model="ruleForm"
        >
          <el-form-item label="在线课程标题：" prop="name">
            <el-col :span="12">
              <el-input v-model="ruleForm.title" placeholder="请输入标题" />
            </el-col>
          </el-form-item>

          <el-form-item label="在线课程时间：" prop="data">
            <el-col :span="12">
              <el-date-picker
                v-model="ruleForm.startTime"
                :disabled="$route.query && $route.query.param? true : false"
                style="width: 100%;"
                type="datetime"
                format="yyyy-MM-dd HH"
                placeholder="选择时间"
              />
            </el-col>
          </el-form-item>

          <el-form-item label="封面图片：">
            <el-col :span="12">
              <el-upload
                class="avatar-uploader"
                :action="action"
                :header="uploadHeader"
                :data="uploadForm"
                :show-file-list="false"
                :on-success="uploadSuccess"
                :before-upload="beforeUpload"
              >
                <div class="uploader-text-box" style="width: 100%; height: 100%;">
                  <img v-if="ruleForm.coverImg" :src="ruleForm.coverImg" class="avatar" />
                  <div v-else>
                    <i class="el-icon-plus avatar-uploader-icon uploader-icon" />
                    <div class="el-upload__text upload__text" style="font-size:16px;">上传文件</div>
                  </div>
                </div>
              </el-upload>
            </el-col>
          </el-form-item>

          <el-form-item v-if="options.teachingTarget" label="教学对象：" prop="teachingTarget">
            <el-col :span="12">
              <el-select
                v-model="ruleForm.teachingTarget.cateId"
                style="width: 100%;"
                placeholder="请输入或选择标签"
                :disabled="$route.query && $route.query.param? true : false"
                @change="getSubject(ruleForm.teachingTarget.cateId)"
              >
                <el-option
                  v-for="item in options.teachingTarget"
                  :key="item.cateId"
                  :label="item.itemName"
                  :value="item.cateId"
                />
              </el-select>
            </el-col>
          </el-form-item>

          <el-form-item label="学段-学科：">
            <!-- prop="subject" -->
            <el-col
              v-if="ruleForm.teachingTarget && options.phase && options.phase.categoryVoList"
              :span="6"
            >
              <el-select
                v-model="ruleForm.phase.cateId"
                :disabled="$route.query && $route.query.param? true : false"
                style="width: 100%;"
                placeholder="请输入或选择标签"
                @change="handleItemChange(ruleForm.phase.cateId)"
              >
                <el-option
                  v-for="item in options.phase.categoryVoList"
                  :key="item.cateId"
                  :label="item.itemName"
                  :value="item.cateId"
                />
              </el-select>
            </el-col>
            <el-col v-else :span="6">
              <el-select v-model="ruleForm.phase" disabled placeholder="请选择">
                <el-option
                  v-for="item in options.phase.categoryVoList"
                  :key="item.cateId"
                  :label="item.itemName"
                  :value="item.cateId"
                />
              </el-select>
            </el-col>

            <el-col
              v-if="
                ruleForm.phase &&
                  options.subject &&
                  options.subject.categoryVoList
              "
              :span="6"
            >
              <el-select
                v-model="ruleForm.subject.cateId"
                style="width: 100%;"
                placeholder="请输入或选择标签"
                :disabled="$route.query && $route.query.param? true : false"
              >
                <el-option
                  v-for="item in options.subject.categoryVoList"
                  :key="item.cateId"
                  :label="item.itemName"
                  :value="item.cateId"
                />
              </el-select>
            </el-col>
            <el-col v-else :span="6">
              <el-select v-model="ruleForm.subject" disabled placeholder="请输入或选择标签">
                <el-option
                  v-for="item in options.subject.categoryVoList"
                  :key="item.cateId"
                  :label="item.itemName"
                  :value="item.cateId"
                />
              </el-select>
            </el-col>
          </el-form-item>

          <!-- 栏目分类 -->
          <el-form-item v-if="options.findColumnTags" label="分类：">
            <el-col :span="12">
              <el-cascader
                v-model="ruleForm.category"
                style="width: 100%;"
                :options="options.findColumnTags"
                :props="{
                  multiple: true,
                  value: 'tagsId',
                  label: 'tagsName',
                  children: 'sub',
                  checkStrictly: true
                }"
                clearable
                filterable
                @keyup.enter.native="tabsKeyup($event, 1)"
              />
            </el-col>
          </el-form-item>

          <el-form-item v-if="options.tagList" label="标签：">
            <el-col :span="12">
              <el-cascader
                v-model="ruleForm.tag"
                style="width: 100%;"
                :options="options.tagList"
                :props="{
                  multiple: true,
                  value: 'tagsId',
                  label: 'tagsName',
                  children: 'sub',
                  checkStrictly: true
                }"
                filterable
                clearable
                @keyup.enter.native="tabsKeyup($event, 2)"
              />
            </el-col>
          </el-form-item>

          <el-form-item label="在线课程介绍：" prop="atvDescribe">
            <el-col :span="23">
              <editor v-model="ruleForm.atvDescribe" @input="newContent" />
            </el-col>
          </el-form-item>
        </el-form>
      </div>

      <div class="button-box">
        <button class="default" @click="backCli">取消</button>
        <button class="submit" @click="onSubmit('ruleForm')">保存</button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getLiveDetail,
  findColumnTags,
  findByPCateId,
  findTagsList,
  updateLive
} from '../../../api/activity';

import { getTagsItems, getParents } from '@/utils/categoryOrTags';
import { preUpload } from '@/api/uploads';
// import VueUeditorWrap from 'vue-ueditor-wrap';
import Tinymce from '@/components/Tinymce/index';
export default {
  name: 'LiveEditOrAdd',
  components: {
    editor: Tinymce
  },
  data () {
    return {
      disabled: false,
      action: 'https://yes910-pub.obs.cn-south-1.myhuaweicloud.com',
      uploadHeader: {
        'Content-Type': 'multipart/form-data'
      },
      uploadForm: {},
      options: {
        teachingTarget: '',
        phase: '',
        subject: '',
        categoryList: '',
        findColumnTags: '',
        tagList: ''
      },
      ruleForm: {
        title: '',
        name: '',
        coverImg: '',
        region: '',
        descs: '',
        teachingTarget: '',
        tag: [],
        subject: [],
        atvDescribe: '是富文本吧',
        category: ''
      },
      rules: {
        title: [{ required: true, message: '请输入标题!', trigger: 'blur' }],
        region: [
          { required: true, message: '请选择教研活动!', trigger: 'change' }
        ],
        coverImg: [
          { required: true, message: '请上传封面图片!', trigger: 'change' }
        ],
        teachingTarget: [
          {
            required: true,
            message: '请至少选择一个教学成长',
            trigger: 'change'
          }
        ],
        subject: [
          {
            required: true,
            message: '请至少选择一个学段-学科!',
            trigger: 'change'
          }
        ],
        category: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个分类',
            trigger: 'change'
          }
        ],
        tag: [
          {
            required: true,
            message: '请至少选择一个标签',
            trigger: 'change'
          }
        ],
        atvDescribe: [
          { required: true, message: '请输入标题!', trigger: 'blur' }
        ]
      }
    };
  },

  created () {
    if (this.$route.query.param) {
      this.init();
    } else {
      this.$router.push({
        path: '/activity/list',
        params: {
          tabsName: 'Live'
        }
      });
      return;
    }
  },
  methods: {
    uploadSuccess (res, file) {
      console.log(this.ruleForm.coverImg);
      // console.log('file:', URL.createObjectURL(file.raw));
      this.ruleForm.coverImg = URL.createObjectURL(file.raw);
      this.ruleForm.coverImg = this.ruleForm.cover;
    },
    beforeUpload (file) {
      const imgStr = /\.(jpg|jpeg|png|JPG|PNG|JPEG)$/;
      if (!imgStr.test(file.name)) {
        this.$message.error('上传格式不对，请重新上传!');
        return false;
      }
      let continueUpload = false;
      return new Promise((resolve, reject) => {
        preUpload({
          biz: 'OPEN',
          name: file.name,
          size: file.size
        }).then(res => {
          this.action = res.data.action;
          this.uploadForm = res.data.parameters;
          continueUpload = true;
          this.ruleForm.cover = res.data.uri;
          resolve(continueUpload);
        }).catch(err => {
          reject(continueUpload);
        });
      });
    },

    // 获取教学成长-选项
    getTeachingTarget () {
      findByPCateId({
        bizTypeEnum: 'WEB_CAST'
      }).then(res => {
        this.options.teachingTarget = res.data.categoryVoList;
        this.getSubject(this.ruleForm.teachingTarget.cateId);
      });
    },

    // 点击教学成长 获取学段-选项
    getSubject (pCateId) {
      findByPCateId({
        bizTypeEnum: 'WEB_CAST',
        pCateId: pCateId
      }).then(res => {
        this.options.phase = res.data;
        this.handleItemChange(this.ruleForm.phase.cateId);
      });
    },
    // 点击学段  获取 学科-选项
    handleItemChange (val) {
      findByPCateId({
        bizTypeEnum: 'WEB_CAST',
        pCateId: val
      }).then(res => {
        this.options.subject = res.data;
      });

      this.getSelection(); // 更新栏目分类+标签选项
    },

    newContent (val) {
      this.ruleForm.atvDescribe = val;
    },
    backCli () {
      this.$router.go(-1);
    },
    tabsKeyup (e, index) {
      var obj;

      switch (index) {
        case 1: // 分类
          obj = {
            tagsId: this.options.findColumnTags.length,
            tagsName: e.target.value,
            children: []
          };
          this.options.findColumnTags.push(obj);
          break;
        case 2: // 标签
          obj = {
            tagsId: this.options.length,
            tagsName: e.target.value
          };
          this.options.tagList.push(obj);
          break;
      }
    },
    // 获取选项
    async getSelection () {
      var teachingCode = this.ruleForm.teachingTarget.itemCode;
      var phaseCode = this.ruleForm.phase.itemCode;
      var subjectCode = this.ruleForm.subject.itemCode;
      var columnObj = {
        growthClassify: teachingCode || null,
        stageList: [phaseCode] || null,
        subjectList: [subjectCode] || null
      };
      // 查找栏目分类选项
      await findColumnTags(columnObj).then(res => {
        this.options.findColumnTags = res.data;
        var categoryList = [];
        if (this.ruleForm.categoryList && this.ruleForm.categoryList.length > 0) {
          this.ruleForm.categoryList.map(item => {
            if (item.tagList && item.tagList.length > 0) {
              item.tagList.map(items => {
                if (getParents(this.options.findColumnTags, items.tagsId, 'tagsId') !== undefined) {
                  categoryList.push(getParents(this.options.findColumnTags, items.tagsId, 'tagsId').reverse());
                }
              });
            }
          });
        }
        console.log('categoryList:', categoryList);
        this.ruleForm.category = categoryList;
      });

      var tagsObj = {
        growthClassify: teachingCode || null,
        stageId: phaseCode || null,
        subjectId: subjectCode || null,
        tagsKindEnum: 'WEB_CAST',
        tagsTypeEnum: 'CATEGORY_TAGS'
      };
      // 查询标签选项
      await findTagsList(tagsObj).then(res => {
        this.options.tagList = res.data;
        var tagList = [];
        if (this.ruleForm.tagList && this.ruleForm.tagList.length > 0) {
          this.ruleForm.tagList.map(item => {
            if (item.tagList && item.tagList.length > 0) {
              item.tagList.map(items => {
                if (getParents(this.options.tagList, items.tagsId, 'tagsId') !== undefined) {
                  tagList.push(getParents(this.options.tagList, items.tagsId, 'tagsId').reverse());
                }
              });
            }
          });
        }
        console.log('tagList:', tagList);
        this.ruleForm.tag = tagList;
      });
    },
    async init () {
      // 获取详情
      await getLiveDetail(this.$route.query.param).then(res => {
        for (var i in res.data) {
          if (
            typeof res.data[i] === 'object' &&
            JSON.stringify(res.data[i]) === '{}'
          ) {
            res.data[i] = '';
          }
        }
        this.ruleForm = res.data;
        if (this.ruleForm.teachingTarget === '') {
          this.ruleForm.teachingTarget = {
            cateId: '',
            itemName: '',
            itemCode: ''
          };
        }
        if (this.ruleForm.phase === '') {
          this.ruleForm.phase = {
            cateId: '',
            itemName: '',
            itemCode: ''
          };
        }
        if (this.ruleForm.subject === '') {
          this.ruleForm.subject = {
            cateId: '',
            itemName: '',
            itemCode: ''
          };
        }

        // 分类
        if (this.ruleForm.categoryList === '') {
          this.ruleForm.categoryList = [{
            tagList: []
          }];
        }
        // 获取教学对象 - 选项
        this.getTeachingTarget();
      });
    },

    // 降维去重
    reduceDimension (arr) {
      const newArr = [];
      const toArr = function (arr) {
        arr.forEach(function (item) {
          item.sub instanceof Array ? toArr(item.sub) : newArr.push(item.tagsId);
        });
      };
      for (var i in arr) {
        newArr.push(arr[i].tagsId);
        toArr(arr);
      }
      var newArr_ = newArr.filter(
        (self, index, newArr) => index === newArr.indexOf(self)
      );
      return newArr_;
    },

    // 降维
    reduceTagList (arr) {
      const newArr = [];
      for (var i in arr) {
        newArr.push(arr[i]);
      }
      const toArr = function (arr) {
        arr.forEach(function (item) {
          item.sub instanceof Array ? toArr(item.sub) : newArr.push(item);
        });
      };
      toArr(arr);
      var newArr_ = newArr.filter(
        (self, index, newArr) => index === newArr.indexOf(self)
      );
      return newArr_;
    },

    onSubmit (formName) {
      var getTime = new Date(this.ruleForm.startTime).getTime();
      this.ruleForm.newData = this.getTimes(getTime);
      this.$refs[formName].validate(valid => {
        if (valid) {
          for (var i in this.ruleForm) {
            if (!this.ruleForm[i]) {
              this.ruleForm[i] = '';
            }
          }

          // console.log(this.options.teachingTarget)
          var teachingTarget, phase, subject;

          // 教学对象
          if (this.ruleForm.teachingTarget) {
            teachingTarget = this.options.teachingTarget.filter(
              item => item.cateId === this.ruleForm.teachingTarget.cateId
            );
          }

          // 学段
          if (this.ruleForm.phase) {
            phase = this.options.phase.categoryVoList.filter(
              item => item.cateId === this.ruleForm.phase.cateId
            );
          }

          // 学科
          if (this.ruleForm.subject && this.options.subject) {
            subject = this.options.subject.categoryVoList.filter(
              item => item.cateId === this.ruleForm.subject.cateId
            );
          }

          // 分类
          if (this.ruleForm.category && this.ruleForm.category.length > 0) {
            this.ruleForm.categoryList = [];
            this.ruleForm.category.map(item => {
              var items = this.options.findColumnTags.filter(
                data => data.tagsId === item[0]
              );
              this.ruleForm.categoryList.push(items[0]);
            });
          }

          // 标签
          if (this.ruleForm.tag && this.ruleForm.tag.length > 0) {
            var arr = this.reduceTagList(this.options.tagList);
            this.ruleForm.tagsList = [];
            this.ruleForm.tag.map(item => {
              var items = arr.filter(
                data => item[item.length - 1] === data.tagsId
              );
              this.ruleForm.tagsList.push(items[0]);
            });
          }

          // 降维去重
          // var newArr = []
          // newArr = this.reduceDimension(this.options.tagList, newArr)

          var data = {
            activityId: this.$route.query.param,
            atvDescribe: this.ruleForm.atvDescribe,
            categoryList: this.ruleForm.categoryList
              ? this.ruleForm.categoryList
              : '', // 栏目分类
            coverImg: this.ruleForm.cover ? this.ruleForm.cover : this.ruleForm.coverImg, // 上传 - 未处理
            endTime: this.ruleForm.endTime,
            enrollFee: this.ruleForm.enrollFee,
            parentId: this.ruleForm.parentId,
            phase: phase && phase.length > 0 ? phase[0].itemCode : '', // 学段
            quota: this.ruleForm.quota,
            startTime: this.ruleForm.startTime,
            subject: subject && subject.length > 0 ? subject[0].itemCode : '', // 学科
            tagList: this.ruleForm.tagsList && this.ruleForm.tagsList.length > 0 ? this.ruleForm.tagsList : '', // 标签 - 未处理
            teachingTarget:
              teachingTarget && teachingTarget.length > 0
                ? teachingTarget[0].itemCode
                : '', // 教学对象
            title: this.ruleForm.title
          };

          updateLive(data).then(res => {
            // console.log(res.data);
            this.$router.push({
              path: '/activity/list',
              params: {
                tabsName: 'Live'
              }
            });
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      //       var birthday = new Date("July 21, 1983 01:15:00")
      // document.write(birthday.getDate())
    },

    // 获取 年月日 时
    getTimes (getTime) {
      var date = new Date(getTime); // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y, M, D, h, m, s; // 年月日 时分秒
      Y = date.getFullYear() + '-';
      M =
        (date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1) + '-';
      D = this.timeChange(date.getDate()) + ' ';
      h = this.timeChange(date.getHours()) + ':';
      m = this.timeChange(date.getMinutes()) + ':';
      s = this.timeChange(date.getSeconds());

      return Y + M + D + this.timeChange(date.getHours());
    },
    // 小于10加0
    timeChange (t) {
      if (t < 10) {
        return '0' + t;
      } else {
        return t;
      }
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.liveEditOrAdd {
  .avatar-uploader {
    width: 480px;
    height: 270px;
    background: rgba(0, 0, 0, 0.02) !important;
    border-radius: 16px;
    border: 1px dashed rgba(0, 0, 0, 0.15);
    border-radius: 8px;
    overflow: hidden;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    margin: 0 auto;
    height: 100%;
    display: block;
  }

  .step {
    span {
      margin: 0 8px;
    }
    .el-input {
      width: 90% !important;
    }
    .step-btn {
      margin-left: 20px;
      margin-top: 10px;
    }
  }

  .crumbs-box {
    background-color: white;
    height: 46px;
    padding-left: 40px;
    .el-breadcrumb {
      line-height: 40px;
    }
  }
  .content-box {
    padding: 40px;
    background: rgba(245, 246, 250, 1);
    .live-title {
      font-size: 20px;
      font-family: MicrosoftYaHei;
      color: rgba(0, 0, 0, 0.85);
      line-height: 28px;
    }

    .teaching-box {
      background-color: white;
      margin-top: 24px;
      padding-bottom: 16px;
      border-radius: 16px;
      .title {
        border-bottom: 1px solid #d9d9d9;
        line-height: 46px;
        padding: 0 40px;
        font-size: 16px;
        font-family: MicrosoftYaHei;
        color: rgba(0, 0, 0, 0.85);
      }

      .teaching-form {
        margin-top: 40px;
        padding: 0 40px;

        .uploader-icon {
          margin-top: 96px;
          line-height: 40px;
          height: 40px;
          margin-bottom: 6px;
        }

        .upload__text {
          font-family: MicrosoftYaHei;
          color: rgba(0, 0, 0, 0.45);
          line-height: 24px;
          margin-bottom: 4px;
        }
      }

      .upload-demo {
        border: 1px solid red;

        width: 480px;
        height: 270px;
        background: rgba(0, 0, 0, 0.02);
        border-radius: 16px;
        // border: 1px solid rgba(0, 0, 0, 0.15);
      }
      .textarea {
        height: 300px;
        padding: 20px;
        background: rgba(0, 0, 0, 0.02);
        border-radius: 4px;
        border: 1px solid rgba(0, 0, 0, 0.15);
      }
    }
    .button-box {
      margin-top: 24px;
      .default {
        width: 94px;
        height: 40px;
        background: rgba(255, 255, 255, 1);
        border-radius: 4px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        margin-right: 30px;
      }
      .submit {
        width: 128px;
        height: 40px;
        border: none;
        background: rgba(84, 184, 123, 1);
        border-radius: 4px;

        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);
        line-height: 24px;
        cursor: pointer;
      }
    }
  }
}
</style>
